package com.wfs.suanfa.thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: wfs
 * @Date: 2020/4/17 09:17
 * @Description:
 */
public class CountDownLatchTest {
    static ExecutorService executor = new ThreadPoolExecutor(10, 20, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2));

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        List<Future<Integer>> list1 = new ArrayList<Future<Integer>>();
        try {
            System.out.println(System.currentTimeMillis());
            for (Integer integer : list) {
                CalRun calRun = new CalRun(integer,countDownLatch);
                //executor.submit(calRun)并不会执行代码，而是在future.get时才会执行并且抛出存在的bug
                Future<Integer> submit = executor.submit(calRun);
                list1.add(submit);
            }
            System.out.println("await:"+System.currentTimeMillis());
            countDownLatch.await(3, TimeUnit.SECONDS);
            System.out.println("endit:"+System.currentTimeMillis());
            for (Future<Integer> integerFuture : list1) {
                Integer integer = integerFuture.get();
                System.err.println(integer);
            }
            System.out.println("完成:"+System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executor.shutdown();
            System.err.println(countDownLatch.getCount());
            System.out.println("完成:"+System.currentTimeMillis());
        }
    }

}

class CalRun implements Callable<Integer> {
    private Integer temp;
    private CountDownLatch countDownLatch;
    public CalRun(Integer temp, CountDownLatch countDownLatch) {
        this.temp = temp;
        this.countDownLatch=countDownLatch;
    }

    public Integer call() throws Exception {
        if (temp == 1) {
            Thread.sleep(4000);
        }
        //
        int i = this.temp * 10/(temp-4);
        countDownLatch.countDown();
        return i;
    }
}